package com.android.djlmapp.token;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.android.djlmapp.activity.login.LoginActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.model.home.RefTokenInfo;
import com.android.djlmapp.server.RefreshService;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;

import java.util.List;

/**
 * token 过期后先刷新一次token,失败就退出登录
 */

public class WebTokenUtils {
    private int code;
    private String mmsg;
    private String token;
    private String version;
    private String network;
    private String user_name;
    private String user_password;
    private String push_id;
    private String phone_os;
    private String phone_type;
    private String phone_brand;
    private String phone_imei;
    private String phone_gps;
    private String phone_num;
    private String sign;
    private Activity mContext;
    private final UserInfoUtils userInfoUtilsInstance;

    public WebTokenUtils(Activity context, RefreshTokenListener listener) {
        userInfoUtilsInstance = UserInfoUtils.getUserInfoUtilsInstance();
        this.mContext = context;
        this.mRefreshTokenListener = listener;
    }

    public void refreshServ() {

        token = userInfoUtilsInstance.getToken();
        version = userInfoUtilsInstance.getVersion();
        network = userInfoUtilsInstance.getNetWork();
        user_name = userInfoUtilsInstance.getUserName();
        user_password = userInfoUtilsInstance.getPwd();
        push_id = userInfoUtilsInstance.getPushId();
        phone_os = userInfoUtilsInstance.getPhoneOs();
        phone_type = userInfoUtilsInstance.getPhoneType();
        phone_brand = userInfoUtilsInstance.getPhoneBrand();
        phone_imei = userInfoUtilsInstance.getPhoneImei();
        phone_gps = userInfoUtilsInstance.getPhoneGps();
        phone_num = userInfoUtilsInstance.getPhoneNum();

        MyApplication.getInstance().getHttpTools().login(network, phone_num, push_id,
                phone_brand, phone_gps, phone_imei, phone_os, phone_type, "2",
                user_name, user_password, mStringCallback);

    }

    private StringCallback mStringCallback = new StringCallback() {
        @Override
        public void onSuccess(com.lzy.okgo.model.Response<String> response) {
            try {
                String body = response.body();
                Gson gson = new Gson();
                RefTokenInfo loginInfo = gson.fromJson(body, RefTokenInfo.class);
                code = loginInfo.getCode();
                mmsg = loginInfo.getMsg();
                Log.e("loginInfo", "code: " + code);
                if (code < 1000) {
                    token = loginInfo.getToken();
                    userInfoUtilsInstance.setToken(token);
                    mRefreshTokenListener.refreshTokenSuc(token);
                } else {
                    mRefreshTokenListener.refreshOnFail();
                }
            } catch (Exception e) {
                ToastUtils.showShortToast(mContext, "数据解析异常");
                exitLogin();
            }

        }

        @Override
        public void onError(com.lzy.okgo.model.Response<String> response) {
            super.onError(response);
            Log.e("项目异常", "------过期token网络错误------");
            String body = response.body();
            if (body.contains("数据解析异常")) {
                ToastUtils.showShortToast(mContext, "登录异常");
            } else {
                ToastUtils.showShortToast(mContext, "网络或服务器错误");
            }
            mRefreshTokenListener.refreshOnErr();
        }
    };

    private RefreshTokenListener mRefreshTokenListener;

    public interface RefreshTokenListener {
        void refreshTokenSuc(String token);

        void refreshOnFail();

        void refreshOnErr();
    }

    public void setRefreshTokenListener(RefreshTokenListener listener) {
        this.mRefreshTokenListener = listener;
    }

    private void exitLogin() {
        ToastUtils.showShortToast(mContext, "登录过期,请重新登录");
        PrefUtils.putBoolean(ConstantsValue.IS_LOG, false);
        PrefUtils.putString(ConstantsValue.TOKEN, "");
        mContext.stopService(new Intent(mContext, RefreshService.class));
        Context ctx = (Context) mContext;
        boolean foreground = isForeground(ctx, LoginActivity.class.getName());
        Log.e("项目异常", "------TokenExpiredUtils---foreground------" + foreground);
        if (!foreground) {
            Intent intent = new Intent(mContext,
                    LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            mContext.finish();
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
